/**
 * AnalyzeErrorsBase.java
 *
 * Copyright (c) Viorel Tacliciu 2009. All Rights Reserved.
 *
 * This source file may not be copied, modified or redistributed,
 * in whole or in part, in any form or for any reason, without the express
 * written consent of Viorel Tacliciu. 
 **/
package ro.prjmanager.core.list;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ListTag extends BodyTagSupport {
    String className;
    private ListClassProcessor listClassProcessor;
    PageContext pageContext;
    private String methodForFilter;
    private String filterPair;
    private String listenHtmlElem;
    private Boolean loadAfterFilter;
    private List<ListenerTag> listenerTagList;
    private Boolean cumulateFilters;
    private String resetCumlateOnListener;

    public PageContext getPageContext() {
        return pageContext;
    }

    public void setPageContext(PageContext pageContext) {
        this.pageContext = pageContext;
    }

    private static Log log = LogFactoryImpl.getLog(ListTag.class);

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        listClassProcessor = new ListClassProcessor(className);
        this.className = className;
    }

    public Boolean isLoadAfterFilter() {
        return loadAfterFilter;
    }

    public void setLoadAfterFilter(Boolean loadAfterFilter) {
        this.loadAfterFilter = loadAfterFilter;
    }

    public int doStartTag() throws JspException {
        listenerTagList = null;
        return super.doStartTag();
    }

    @Override
    public int doAfterBody() throws JspException {
        try {
            getBodyContent().getEnclosingWriter().println(
                    listClassProcessor.process(methodForFilter, filterPair, loadAfterFilter).replaceAll("%context_path%",
                            getPageContext().getServletContext().getContextPath()));
            processListeners();
        } catch (IOException e) {
            log.error(e);
        } catch (ClassNotFoundException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        } catch (InstantiationException e) {
            log.error(e);
        }
        return EVAL_BODY_INCLUDE;
    }

    private void processListeners() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        if (listenerTagList != null && listenerTagList.size() > 0) {

            StringBuilder sb = new StringBuilder();
            sb.append("<script type=\"text/javascript\">\n");
            for (ListenerTag listenerTag : listenerTagList) {
                sb.append("$(\"#").append(listenerTag.getHtmlId()).append("\").bind('").append(listenerTag.getEventName()).append("',function(){\n");
                sb.append("var v=").append("$(\"#").append(listenerTag.getFilterHtmlId()).append("\").val();\n");
                sb.append("filterGridByListener('").append(listClassProcessor.getIdList()).append("','").append(methodForFilter).append("',");
                sb.append(cumulateFilters != null ? cumulateFilters : false).append(",'").append(listenerTag.getId()).append("','");
                sb.append(getResetCumlateOnListener()).append("','").append(listenerTag.getFilterHtmlId()).append("',v);");
                sb.append("    });");
            }
            sb.append("</script>");
            getBodyContent().getEnclosingWriter().println(sb.toString());
        } else if (listenHtmlElem != null && listenHtmlElem.length() > 0) {
            Map<String, String> listens = Json.fromJson(listenHtmlElem);
            Set<String> keys = listens.keySet();
            StringBuilder sb = new StringBuilder();
            if (keys != null && keys.size() > 0) {
                sb.append("<script type=\"text/javascript\">");
                for (String key : keys) {
                    String funct = listens.get(key);
                    sb.append("$(\"#").append(key).append("\").bind(\"").append(funct).append(".").append(key).append("\",function() {\n");
                    sb.append("var v=").append("$(\"#").append(key).append("\").val();\n");

                    sb.append("filterGridByListener('").append(listClassProcessor.getIdList()).append("','").append(methodForFilter).append("',");
                    sb.append(cumulateFilters != null ? cumulateFilters : false).append(",'").append(key).append("','");
                    sb.append(getResetCumlateOnListener()).append("','").append(key).append("',v);");

                    sb.append("    });");
                }
                sb.append("</script>");
            }
            getBodyContent().getEnclosingWriter().println(sb.toString());
        }
    }

    public String getMethodForFilter() {
        return methodForFilter;
    }

    public void setMethodForFilter(String methodForFilter) {
        this.methodForFilter = methodForFilter;
    }

    public String getFilterPair() {
        return filterPair;
    }

    public void setFilterPair(String filterPair) {
        this.filterPair = filterPair;
    }

    public String getListenHtmlElem() {
        return listenHtmlElem;
    }

    public void setListenHtmlElem(String listenHtmlElem) {
        this.listenHtmlElem = listenHtmlElem;
    }

    public List<ListenerTag> getListenerTagList() {
        return listenerTagList;
    }

    public void setListenerTagList(List<ListenerTag> listenerTagList) {
        this.listenerTagList = listenerTagList;
    }

    public Boolean isCumulateFilters() {
        return cumulateFilters;
    }

    public void setCumulateFilters(Boolean cumulateFilters) {
        this.cumulateFilters = cumulateFilters;
    }

    public String getResetCumlateOnListener() {
        return resetCumlateOnListener;
    }

    public void setResetCumlateOnListener(String resetCumlateOnListener) {
        this.resetCumlateOnListener = resetCumlateOnListener;
    }
}
